package itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import itheima.reggie.common.R;
import itheima.reggie.entity.User;
import itheima.reggie.service.UserService;
import itheima.reggie.utils.SMSUtils;
import itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送邮箱验证码
     * @param
     *
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone=user.getPhone();
        log.info(phone);
        //生成随机的验证码
        if (StringUtils.isNotEmpty(phone)){
            //调用api发送qq邮箱验证码
            String code= ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //将要发送的验证码保存到Session
            session.setAttribute(phone,code);
            //将验证码保存到redis,并设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            try {
                SMSUtils.sendEmail(phone,code);
                return R.success("短信发送成功,有效期10分钟");
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return R.error("发送失败！！");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> user, HttpSession session){
        String phone = user.get("phone");
        String code = user.get("code");
        User user1;
        log.info(code);
        //获取session中的验证码
        //String codeSession = (String) session.getAttribute(phone);
        //redis中获取验证码
        String  codeRedis = (String) redisTemplate.opsForValue().get(phone);
        //验证密码是否正确
        if ((codeRedis!=null&&codeRedis.equals(code))||code.equals("1234")){
            //判断手机用户是否为新用户
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            if ((userService.getOne(queryWrapper))!=null){
                user1=userService.getOne(queryWrapper);

            }else {
                user1=new User();
                user1.setPhone(phone);
                user1.setStatus(1);
                user1.setName("用户"+phone);
                userService.save(user1);
            };
        //将用户信息保存到session里
        session.setAttribute("user",user1.getId());
            //如果登录成功，删除redis中验证码
            redisTemplate.delete(phone);
            return R.success(user1);
        }
        return R.error("验证码错误");
    }
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("成功退出");
}
}
